﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Wp.DAL;
using Wp.BLL;
using System.Text;
using System.Web.Caching;

public partial class Controls_TopMenu : System.Web.UI.UserControl
{
    string CacheKey = "menucache";
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }

    public string LoadChildMenu(int ParentId)
    {
        List<TblPostsEntity> menu = TblPostsManager.CreateInstant().SelectTblPostByParent(ParentId, "menu");
        StringBuilder str = new StringBuilder();
        if (ParentId == -1)
            str.Append(" <ul class='mainmenu'>");
        else
            str.Append(" <ul class='sub-menu'>");

        for (int i = 0; i < menu.Count; i++)
        {
            List<TblPostsEntity> menu2 = TblPostsManager.CreateInstant().SelectTblPostByParent(menu[i].Id, "menu");
            str.Append("<li class='menu-item'><a href=\"" + menu[i].Url + "\" title='" + menu[i].Title + "'>" + menu[i].Title + "</a>");
            if (menu2.Count > 0)
            {
                str.Append(LoadChildMenu(menu[i].Id));
            }
            str.Append("</li>");
        }
        str.Append(" </ul>");
        return str.ToString();
    }
    public string GetMenu()
    {
        if (HttpRuntime.Cache[CacheKey] == null)

        {
            CacheMenu();
        }
        return HttpRuntime.Cache[CacheKey].ToString();
    }
    void CacheMenu()
    {
        string str = LoadChildMenu(-1);
        HttpRuntime.Cache.Insert(CacheKey, str, null, DateTime.UtcNow.AddMinutes(10), TimeSpan.Zero, CacheItemPriority.Default, new CacheItemRemovedCallback(CachedItemRemoveCallBack));
    }
    private void CachedItemRemoveCallBack(string key, object value, CacheItemRemovedReason reason)
    {
        if (HttpRuntime.Cache[CacheKey] == null)
        {
            CacheMenu();
        }
    }
}